<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="geometry" content="interval">
  <link rel="stylesheet" href="./assets/common.css">
  <title>Stock Index Chart</title>
</head>

<body>
  <div id="canvas"></div>
  <script src="./assets/jquery-3.2.1.min.js"></script>
  <script src="./assets/data-set.min.js"></script>
  <script src="../build/g2.js"></script>

  <script>
    $.get('./data/stocks.csv', csv => {
      const ds = new DataSet({
        state: {
          date: 'Jan 1 2005'
        }
      });
      const priceByKey = {};
      const srcDv = new DataSet.View(ds, {
        watchingStates: []
      });
      srcDv
        .source(csv, {
          type: 'csv'
        })
        .transform({
          type: 'map',
          callback(row) {
            row.key = `${row.symbol}-${row.date}`;
            row.price = parseInt(row.price, 10);
            priceByKey[row.key] = row.price;
            return row;
          }
        });
      const destDv = new DataSet.View(ds, {
        watchingStates: [ 'date' ]
      });
      destDv.source(srcDv)
        .transform({
          type: 'map',
          callback(row) {
            const key = `${row.symbol}-${ds.state.date}`;
            const indexedPrice = priceByKey[key];
            row.rate = (!indexedPrice || indexedPrice === 0) ? 0 : (row.price - indexedPrice) / indexedPrice;
            return row;
          }
        });

      const chart = new G2.Chart({
        container: 'canvas',
        forceFit: true,
        height: window.innerHeight,
        padding: [ 'auto', 'auto', 30, 'auto' ],
        animate: false
      });
      chart.scale({
        date: {
          type: 'time'
        },
        rate: {
          formatter: val => `${(val * 100).toFixed(1)}%`
        }
      });
      chart.axis('rate', {
        grid: {
          hightLightZero: true
        }
      });
      chart.axis('date', false);
      chart.legend({
        attachLast: true
      });
      chart.tooltip(false);
      chart.source(destDv);
      chart.line()
        .position('date*rate')
        .color('symbol');

      let dateLineGuide;
      chart.on('mousemove', ev => {
        const records = chart.getSnapRecords(ev);
        if (G2.Util.isArray(records) && records.length) {
          const date = records[0]._origin.date;
          if (date !== ds.state.date) {
            if (dateLineGuide) {
              dateLineGuide.clear();
              dateLineGuide = null;
            }
            ds.setState('date', records[0]._origin.date);
            dateLineGuide = chart.guide().line({
              start: [ date, 'start' ],
              end: [ date, 'end' ],
              lineStyle: {
                lineDash: null,
                stroke: 'red'
              },
              text: {
                autoRotate: false,
                position: 'start',
                content: ds.state.date,
                style: {
                  fill: 'red',
                  textAlign: 'center'
                },
                offsetY: 22
              }
            });
          }
        }
      });
      chart.render();
    });
  </script>
</body>

</html>
